#include <stdio.h>
#include "user_wifi.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "user_nvs_flash.h"
#include "string.h"



wifi_country_t config = {
    .cc = "01",
    .schan = 1,
    .nchan = 11,
    .policy = WIFI_COUNTRY_POLICY_AUTO,
};

wifi_scan_config_t scan_config = {
    .show_hidden = true/**< Enable it to scan AP whose SSID is hidden */
}
;

void user_wifi_task(void)
{
    const char *Debug = "WIFI_TASK";

    wifi_country_t user_wifi_country;

    ESP_LOGI(Debug, "wifi_task \n");

    ESP_LOGI(Debug, "0.初始化NVS存储 \n");
    user_wifi_nvs();

    ESP_LOGI(Debug, "1.WIFI初始化阶段 \n");
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t wifi_config = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&wifi_config);

    esp_wifi_set_mode(WIFI_MODE_STA);

    ESP_LOGI(Debug, "2.WIFI启动化阶段 \n");

    esp_wifi_start();

    ESP_LOGI(Debug, "3.WIFI扫描 \n");
    esp_wifi_set_country(&user_wifi_country);
    esp_wifi_scan_start(&scan_config, true);

    uint16_t ap_num = 0;
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_num));
    ESP_LOGI(Debug, "AP Count = %d \n", ap_num);

    uint16_t max_aps = 20;
    wifi_ap_record_t ap_records[max_aps];
    memset(ap_records , 0 , sizeof(ap_records));

    uint16_t aps_count = max_aps;
    ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&aps_count , ap_records));

    ESP_LOGI(Debug, "AP Count = %d \n", ap_num);

    printf("%30s %s %s %s \n","SSID" , "频道", "强度","MAC地址");

    for(int i = 0 ; i < aps_count ; i++)
    {
        printf("%30s %3d %3d %02X-%02X-%02X-%02X-%02X-%02X \n",ap_records[i].ssid , ap_records[i].primary, ap_records[i].rssi,ap_records[i].bssid[5]
        ,ap_records[i].bssid[4],ap_records[i].bssid[3],ap_records[i].bssid[2],ap_records[i].bssid[1],ap_records[i].bssid[0]);

    }

}
